#pragma once
#include <iostream>
#include <string>
#include <cstdio>
#include <fstream>
#include <set>
#include "Log.hpp"

class Command
{
public:
    Command(const std::string filePath)
        :_safeFilePath(filePath)
    {
        Load(_safeFilePath);
    }
    void Load(const std::string& path)
    {
        std::ifstream in(path.c_str(), std::ios::in);
        if(!in.is_open())
        {
            LOG(FATAL, "conf load error\n");
            exit(1);
        }
        std::string message;
        while(std::getline(in, message))
        {
            _safe_command.insert(message);
            LOG(DEBUG, "load conf : %s\n", message.c_str());
        }
    }
    std::string GetPrefix(const std::string& cmd)
    {
        int n = cmd.size();
        int i = 0;
        while(i < n && !isalpha(cmd[i]))
            i++;
        std::string ret;
        while(i < n && isalpha(cmd[i]))
        {
            ret += cmd[i++];
        }
        return ret;
    }
    std::string Excute(const std::string& cmd)
    {
        std::string prefix = GetPrefix(cmd);
        std::string ret;
        if(_safe_command.count(prefix))
        {
            FILE* pf = popen(cmd.c_str(), "r");
            if(pf == nullptr)
            {
                return "failed";
            }
            char buff[1024];
            while(fgets(buff, sizeof(buff), pf) != nullptr)
            {
                ret += buff;
            }
            pclose(pf);
        }
        else
        {
            ret = "坏人\n";
        }
        return ret;
    }
    ~Command()
    {}
private:
    std::string _safeFilePath;
    std::set<std::string> _safe_command;
};